from flask import request
from flask_restx import Resource, Namespace, fields
from flask_jwt_extended import create_access_token, create_refresh_token, jwt_required, get_jwt_identity
from datetime import datetime
import hashlib

import app1
from app1.models import Zbfwbuser

# 创建命名空间
auth_ns = Namespace('auth', description='Authentication operations')

# 定义用户模型
user_model = auth_ns.model('User', {
    'username': fields.String(required=True, description='Username'),
    'password': fields.String(required=True, description='Password')
})


def md5_hash(password):
    """使用MD5对密码进行加密"""
    return hashlib.md5(password.encode('utf-8')).hexdigest()


@auth_ns.route('/login')
class AuthResource(Resource):
    @auth_ns.expect(user_model)
    def post(self):
        """ 密文密码登录 """
        data = request.get_json()
        user = Zbfwbuser.query.filter_by(t_zbfwb_user_name=data['username']).first()
        if user and user.t_zbfwb_user_passwd == data['password']:
            access_token = create_access_token(identity=user.t_zbfwb_user_id)
            refresh_token = create_refresh_token(identity=user.t_zbfwb_user_id)
            expire_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            return {'access_token': access_token, 'refresh_token': refresh_token, 'expire': expire_time}, 200

        return {'message': 'Invalid credentials'}, 401


@auth_ns.route('/login_plain')
class AuthPlainResource(Resource):
    @auth_ns.expect(user_model)
    def post(self):
        """ 明文密码登录 """
        data = request.get_json()

        # 对密码进行MD5加密
        hashed_password = md5_hash(data['password'])

        # 查询数据库，查找对应用户名和加密后的密码
        user = Zbfwbuser.query.filter_by(t_zbfwb_user_name=data['username']).first()

        # 检查用户名和密码是否匹配
        if user and user.t_zbfwb_user_passwd == hashed_password:
            # 生成访问令牌和刷新令牌
            access_token = create_access_token(identity=user.t_zbfwb_user_id)
            refresh_token = create_refresh_token(identity=user.t_zbfwb_user_id)
            expire_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            return {'access_token': access_token, 'refresh_token': refresh_token, 'expire': expire_time}, 200

        return {'message': 'Invalid credentials'}, 401


@auth_ns.route('/user-info')
class ProtectedResource(Resource):
    @jwt_required()
    # @auth_ns.expect(user_model)  # 使用 user_model 指定输入数据的预期格式
    def post(self):
        current_user = get_jwt_identity()  # 获取当前用户的身份信息,flask_jwt_extended自带功能

        # 假设你的数据库模型包括 Zbfwbuser，以下是一个示例：
        user = Zbfwbuser.query.get(current_user)

        # 如果找到用户，返回用户信息
        if user:
            user_info = {
                'username': user.t_zbfwb_user_name,
                # 添加其他用户信息字段
            }
            return user_info, 200
        return {'message': 'User not found'}, 404
